package com.rzjm.exercise.sys.core.job.service.impl;

import com.rzjm.exercise.common.base.service.impl.BaseServiceImpl;
import com.rzjm.exercise.common.constant.Constant;
import com.rzjm.exercise.common.schedule.quartz.QuartzManager;
import com.rzjm.exercise.common.utils.ScheduleJobUtils;
import com.rzjm.exercise.sys.core.job.dao.TaskDao;
import com.rzjm.exercise.sys.core.job.domain.ScheduleJob;
import com.rzjm.exercise.sys.core.job.domain.TaskDO;
import com.rzjm.exercise.sys.core.job.service.JobService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Service
public class JobServiceImpl extends BaseServiceImpl<TaskDao, TaskDO> implements JobService {

	@Resource
	private TaskDao taskDao;

	@Resource
	QuartzManager quartzManager;

	@Override
	public int remove(Long id) {
		try {
			TaskDO scheduleJob = taskDao.selectById(id);
			if(scheduleJob!=null){
				quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
				return taskDao.deleteById(id);
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
			return 0;
		}
		return 0;
	}

	@Override
	public int batchRemove(Long[] ids) {
		for (Long id : ids) {
			try {
				TaskDO scheduleJob = taskDao.selectById(id);
				quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
			} catch (SchedulerException e) {
				e.printStackTrace();
				return 0;
			}
		}
		List<Long> list = Arrays.asList(ids);
		return taskDao.deleteBatchIds(list);
	}

	@Override
	public void initSchedule() throws SchedulerException {
		// 这里获取任务信息数据
		List<TaskDO> jobList = taskDao.selectByMap(new HashMap<String, Object>(16));
		for (TaskDO scheduleJob : jobList) {
			if ("1".equals(scheduleJob.getJobStatus())) {
				ScheduleJob job = ScheduleJobUtils.entityToData(scheduleJob);
				quartzManager.addJob(job);
			}
		}
	}

	@Override
	public void changeStatus(Long jobId, String cmd) throws SchedulerException {
		TaskDO scheduleJob = taskDao.selectById(jobId);
		if (scheduleJob == null) {
			return;
		}
		if (Constant.STATUS_RUNNING_STOP.equals(cmd)) {
			quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
			scheduleJob.setJobStatus(ScheduleJob.STATUS_NOT_RUNNING);
		} else {
			if (!Constant.STATUS_RUNNING_START.equals(cmd)) {
			} else {
                scheduleJob.setJobStatus(ScheduleJob.STATUS_RUNNING);
                quartzManager.addJob(ScheduleJobUtils.entityToData(scheduleJob));
            }
		}
		updateById(scheduleJob);
	}

}
